package com.cff.netty.anno.self.update;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import org.springframework.beans.factory.annotation.Autowired;

import com.cff.anno.AutoDi;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServerInitializerConfigeration extends ChannelInitializer<SocketChannel> {
	NettyServerInitializerConfigeration nettyServerInitializerConfigeration;
	ChannelHandler channelHandler;
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		if (nettyServerInitializerConfigeration == null) {
			// 以("\n")为结尾分割的 解码器
			pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));

			// 字符串解码 和 编码
			pipeline.addLast("decoder", new StringDecoder());
			pipeline.addLast("encoder", new StringEncoder());
			System.out.println(Thread.currentThread().getName() + "----位置5");
			System.out.println(channelHandler.getClass().getName() + "----位置5");
			ChannelHandler channelHandlerTmp = channelHandler.getClass().newInstance();
			copyProperties(channelHandler, channelHandlerTmp);
			// 自己的逻辑Handler
			pipeline.addLast("handler", channelHandlerTmp);
		}else{
			nettyServerInitializerConfigeration.initChannel(ch);
		}
	}

	public void setNettyServerInitializerConfigeration(
			NettyServerInitializerConfigeration nettyServerInitializerConfigeration) {
		this.nettyServerInitializerConfigeration = nettyServerInitializerConfigeration;
	}
	
	public void setChannelHandler(ChannelHandler channelHandler){
		this.channelHandler = channelHandler;
	}
	
	public void copyProperties(ChannelHandler src,ChannelHandler dst) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
		Field[] fields = src.getClass().getDeclaredFields();
		Field[] dstfields = dst.getClass().getDeclaredFields();
		for (Field f : fields) {
			System.out.println("属性为："+f.getType());
			System.out.println("名称为："+f.getName());
			for (Field dstf : dstfields) {
				if(f.getName().equals(dstf.getName())){
					dstf.setAccessible(true);
					dstf.set(dst, f.get(src));
					break;
				}
			}			
		}
	}

}
